//This file contains the handlers for the /login/device and /login/device/code routes.
import 'dart:io';

import 'package:copilot_proxy/check_auth/check_auth.dart';
import 'package:copilot_proxy/context.dart';

Future<void> postLoginDeviceCode(Context context) async {
  final clientId = context['client_id'];
  if (clientId == null || clientId.isEmpty) {
    context.statusCode = HttpStatus.badRequest;
    return;
  }
  final (userCode, deviceCode) = generateUserCode(clientId);
  final uri = context.request.requestedUri;
  final verificationUri = '${uri.origin}'
      '/login/device?'
      'user_code=$userCode&'
      'client_id=$clientId';
  context.ok();
  context.json({
    'device_code': deviceCode,
    'expires_in': 1800,
    'interval': 5,
    'user_code': userCode,
    'verification_uri': verificationUri,
    'verification_uri_complete': verificationUri,
  });
}

Future<void> getLoginDevice(Context context) => _baseLoginDevice(context, true);

// Future<void> postLoginDevice(Context context) => _baseLoginDevice(context, false);

Future<void> _baseLoginDevice(Context context, bool showPage) async {
  final userCode = context['user_code'];
  final clientId = context['client_id'];
  return checkUserCodeAndClientId(userCode, clientId, context, showPage);
}

void checkUserCodeAndClientId(
  String? userCode,
  String? clientId,
  Context context,
  bool showPage,
) {
  if (userCode == null ||
      userCode.isEmpty ||
      !checkUserCode(userCode) ||
      clientId == null ||
      clientId.isEmpty ||
      !checkClientID(clientId)) {
    context.statusCode = HttpStatus.badRequest;
    return;
  }
  allowDeviceCode(userCode, clientId);
  if (!showPage) return context.noContent();
  final username = getUserInfoByClientId(clientId)?['name'];
  context.ok();
  context.response.headers.contentType = ContentType.html;
  context.write('''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
    <style>
        body, html {
            height: 100%;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: Arial, sans-serif;
        }
        .message {
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="message">
        <h1>Hello $username, you can close this page now.</h1>
    </div>
</body>
</html>
''');
}
